﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Yz.Base;
using Yz.Base.Config;
using Yz.Base.ParaModels;
using Yz.Core.Extensions;
using Yz.DataAccess.ApiAccesses.Interface;

namespace Yz.Web.Controllers
{
    public class FileController : BaseController
    {
        private readonly IWebHostEnvironment _webHostEnv;
        private readonly FileServiceConfig _fileServiceConfig;
        private readonly IApiFileServiceAccess _apiFileServiceAccess;
        public FileController(IWebHostEnvironment webHostEnv, IOptions<FileServiceConfig> fileServiceConfigOps, IApiFileServiceAccess apiFileServiceAccess)
        {
            _webHostEnv = webHostEnv;
            if (fileServiceConfigOps != null)
            {
                _fileServiceConfig = fileServiceConfigOps.Value;
            }
            _apiFileServiceAccess = apiFileServiceAccess;
        }
        /// <summary>
        /// 合并大文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="guid"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> MergeUploadFile(string fileName, string guid)
        {
            var upFile = new VmUpFile();
            if (_fileServiceConfig == null)
            {
                upFile = MergeFile(_webHostEnv, fileName, guid);
            }
            else
            {
                upFile = await _apiFileServiceAccess.MergeUploadFile(new ParaMergeFile()
                {
                    Guid = guid,
                    FileName = fileName,
                    Chunks = 1
                });
            }
            return Json(upFile);
        }

        /// <summary>
        /// 文件上传(大文件分片)
        /// </summary>
        /// <param name="chunk"></param>
        /// <param name="chunks"></param>
        /// <param name="guid"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> UploadBigFile(int? chunk, int? chunks, string guid, IList<IFormFile> files)
        {
            var upFile = new VmUpFile();
            var file = files[0];
            if (_fileServiceConfig == null || _fileServiceConfig.Url.IsEmpty() || _fileServiceConfig.AppId.IsEmpty() || _fileServiceConfig.AppSecret.IsEmpty())
            {
                if (chunks == null || chunks == 1)
                {
                    upFile = await SaveFile(_webHostEnv, FileType.Vdo, file);
                    upFile.Chunk = false;
                    return Json(upFile);
                }
                var chu = Convert.ToInt32(chunk);
                upFile = SaveBigFile(_webHostEnv, chu, guid, file);
                upFile.Chunk = true;
            }
            else
            {
                byte[] bytes = null;
                using (Stream stream = file.OpenReadStream())
                {
                    int dataBufferSize = stream.Length.ToInt();
                    bytes = new byte[dataBufferSize];
                    int currentRead = await stream.ReadAsync(bytes, 0, dataBufferSize);//从数据流中读取bufferSize大小的内容到服务器内存中
                }
                var apiFile = new ApiFile() { Name = file.Name, FileBytes = bytes, FileName = file.FileName, ContentType = file.ContentType };

                if (chunks == null || chunks == 1)
                {
                    upFile = await _apiFileServiceAccess.UploadFile(apiFile);
                    upFile.Chunk = false;
                    return Json(upFile);
                }
                var chu = Convert.ToInt32(chunk);
                upFile = await _apiFileServiceAccess.UploadChunkFile(apiFile, new ParaChunkFile()
                {
                    Chunk = chu,
                    Chunks = chunks.ToInt()
                });
                upFile.Chunk = true;
            }
            return Json(upFile);
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="ft"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("file/uploadfile/{ft:int}/{fi:int}")]
        public async Task<JsonResult> UploadFile(FileType ft, int fi)
        {
            var file = Request.Form.Files.FirstOrDefault();
            var upFile = new VmUpFile();
            if (_fileServiceConfig == null || _fileServiceConfig.Url.IsEmpty() || _fileServiceConfig.AppId.IsEmpty() || _fileServiceConfig.AppSecret.IsEmpty())
            {
                await SaveFile(_webHostEnv, ft, file, fi);
            }
            else
            {
                byte[] bytes = null;
                using (Stream stream = file.OpenReadStream())
                {
                    int dataBufferSize = stream.Length.ToInt();
                    bytes = new byte[dataBufferSize];
                    int currentRead = await stream.ReadAsync(bytes, 0, dataBufferSize);//从数据流中读取bufferSize大小的内容到服务器内存中
                }
                var apiFile = new ApiFile() { Name = file.Name, FileBytes = bytes, FileName = file.FileName, ContentType = file.ContentType };
                upFile = await _apiFileServiceAccess.UploadFile(apiFile);
                upFile.File.Index = fi;
            }
            return Json(upFile);
        }

        /// <summary>
        /// 文档预览（pdf）
        /// </summary>
        /// <returns></returns>
        public ActionResult Pdf(string flPath)
        {
            ViewBag.flPath = flPath;
            return View();
        }
        /// <summary>
        /// 视频播放
        /// </summary>
        /// <param name="flImgPath"></param>
        /// <param name="flPath"></param>
        /// <returns></returns>
        public ActionResult Video(string flImgPath, string flPath)
        {
            ViewBag.flPath = flPath;
            ViewBag.flImgPath = flImgPath;
            return View();
        }

    }
}